package sk.stuba.fiit.foo07.genex.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.activation.MimetypesFileTypeMap;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import sk.stuba.fiit.foo07.genex.beans.Picture;
import sk.stuba.fiit.foo07.genex.common.ResourceHelper;
import sk.stuba.fiit.foo07.genex.dao.PictureDao;
import sk.stuba.fiit.foo07.genex.dao.PictureDaoDerby;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class NewPictureDialog extends javax.swing.JDialog {
    /**
     * 
     */
    private static final long serialVersionUID = 7855093533185184721L;

    private DefaultListModel pictures;
    private PictureDao pDao;
    private Picture[] ret;
    private Picture lastSel;
    private JLabel jLabel5;
    private JTextField jTxtMIME;
    private JTextField jTxtSettings;
    private JLabel jLabel4;
    private JScrollPane jScrollPane2;
    private JTextArea jTxtDesciption;
    private JLabel jLabel3;
    private ResourceHelper resHelp;

    private JLabel jLabel1;
    private JScrollPane jScrPictures;
    private JScrollPane jScrollPane1;
    private JButton jBtnOK;
    private PictureComponent jPreview;
    private JCheckBox jChbResize;
    private JButton jBtnCancel;
    private JSeparator jSeparator2;
    private JButton jBtnAddPicture;
    private JList jLstPictures;
    private JLabel jLabel2;
    private JScrollPane jScrPreview;
    private JSeparator jSeparator1;
    private JTextPane jTxtHint;

    public NewPictureDialog(JDialog frame, Connection c) {
        super(frame);

        resHelp = new ResourceHelper();
        pictures = new DefaultListModel();
        pDao = new PictureDaoDerby(c);
        ArrayList<Picture> dbpixs = null;
        //TODO
        try {
            dbpixs = pDao.getAllPictures();
            for (Picture p : dbpixs) {
                pictures.addElement(p);
            }
        } catch (Exception e) {
        }
        initGUI();
    }

    private void initGUI() {
        try {
            {
                getContentPane().setLayout(null);
                this.setResizable(false);
                this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                this.setTitle("Prida\u0165 obrázky");
                setLocationByPlatform(true);
                {
                    jLabel1 = new JLabel();
                    getContentPane().add(jLabel1);
                    jLabel1.setText("Obrázky v databáze");
                    jLabel1.setBounds(12, 103, 167, 14);
                    jLabel1.setForeground(new java.awt.Color(100, 0, 0));
                }
                {
                    jScrPictures = new JScrollPane();
                    getContentPane().add(jScrPictures);
                    jScrPictures.setBounds(12, 123, 291, 174);
                    {
                        jLstPictures = new JList(pictures);
                        jScrPictures.setViewportView(jLstPictures);
                        jLstPictures.setBackground(new java.awt.Color(255, 255,
                                240));
                        jLstPictures
                                .setForeground(new java.awt.Color(0, 0, 255));
                        jLstPictures.addMouseListener(new MouseAdapter() {
                            @Override
                            public void mouseClicked(MouseEvent evt) {
                                if (evt.getClickCount() == 2)
                                    jBtnOKActionPerformed(new ActionEvent(
                                            jBtnOK, 0, null));
                            }
                        });
                        jLstPictures
                                .addListSelectionListener(new ListSelectionListener() {
                                    public void valueChanged(
                                            ListSelectionEvent evt) {
                                        jLstPicturesValueChanged(evt);
                                    }
                                });
                    }
                }
                {
                    jScrollPane1 = new JScrollPane();
                    getContentPane().add(jScrollPane1);
                    jScrollPane1.setBounds(12, 12, 592, 75);
                    {
                        jTxtHint = new JTextPane();
                        jScrollPane1.setViewportView(jTxtHint);
                        jTxtHint.setBackground(GenexGUI.COMB1_BACKGROUND_COLOR);
                        jTxtHint.setForeground(GenexGUI.COMB1_FOREGROUND_COLOR);
                        jTxtHint.setEditable(false);
                        hint("Info: Mô\u017eete prida\u0165 aj viacero obrázkov nazaz pou\u017eitím klávesov shift, control a my\u0161i.");
                    }
                }
                {
                    jSeparator1 = new JSeparator();
                    getContentPane().add(jSeparator1);
                    jSeparator1.setBounds(12, 93, 592, 10);
                }
                {
                    jScrPreview = new JScrollPane();
                    getContentPane().add(jScrPreview);
                    jScrPreview.setBounds(309, 123, 295, 218);
                    {
                        jPreview = new PictureComponent();
                        jPreview.setMinimumSize(new Dimension(jScrPreview
                                .getSize().width - 3,
                                jScrPreview.getSize().height - 3));
                        jScrPreview.setViewportView(jPreview);
                    }
                }
                {
                    jLabel2 = new JLabel();
                    getContentPane().add(jLabel2);
                    jLabel2.setText("Náh\u013ead");
                    jLabel2.setBounds(309, 103, 75, 14);
                    jLabel2.setForeground(new java.awt.Color(100, 0, 0));
                }
                {
                    jBtnAddPicture = new JButton();
                    getContentPane().add(jBtnAddPicture);
                    jBtnAddPicture.setText("Zo súboru");
                    jBtnAddPicture.setBounds(194, 309, 109, 21);
                    jBtnAddPicture.setMnemonic(java.awt.event.KeyEvent.VK_Z);
                    jBtnAddPicture.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            jBtnAddPictureActionPerformed(evt);
                        }
                    });
                }
                {
                    jChbResize = new JCheckBox();
                    getContentPane().add(jChbResize);
                    jChbResize.setText("v okne");
                    jChbResize.setBounds(508, 345, 96, 18);
                    jChbResize.setForeground(new java.awt.Color(100, 0, 0));
                    jChbResize.setMnemonic(java.awt.event.KeyEvent.VK_K);
                    jChbResize.setSelected(true);
                    jChbResize.setHorizontalTextPosition(SwingConstants.LEFT);
                    jChbResize.setHorizontalAlignment(SwingConstants.RIGHT);
                    jChbResize.addChangeListener(new ChangeListener() {
                        public void stateChanged(ChangeEvent evt) {
                            jChbResizeStateChanged(evt);
                        }
                    });
                }
                {
                    jSeparator2 = new JSeparator();
                    getContentPane().add(jSeparator2);
                    jSeparator2.setBounds(14, 432, 592, 10);
                }
                {
                    jBtnCancel = new JButton();
                    getContentPane().add(jBtnCancel);
                    jBtnCancel.setText("Cancel");
                    jBtnCancel.setBounds(515, 443, 92, 21);
                    jBtnCancel.setMnemonic(java.awt.event.KeyEvent.VK_C);
                    jBtnCancel.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            jBtnCancelActionPerformed(evt);
                        }
                    });
                }
                {
                    jBtnOK = new JButton();
                    getContentPane().add(jBtnOK);
                    jBtnOK.setText("OK");
                    jBtnOK.setBounds(418, 443, 92, 21);
                    jBtnOK.setMnemonic(java.awt.event.KeyEvent.VK_O);
                    jBtnOK.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            jBtnOKActionPerformed(evt);
                        }
                    });
                }
                {
                    jLabel3 = new JLabel();
                    getContentPane().add(jLabel3);
                    jLabel3.setText("Popis");
                    jLabel3.setBounds(12, 321, 109, 14);
                    jLabel3.setForeground(new java.awt.Color(100, 0, 0));
                }
                {
                    jScrollPane2 = new JScrollPane();
                    getContentPane().add(jScrollPane2);
                    jScrollPane2.setBounds(12, 341, 291, 79);
                    {
                        jTxtDesciption = new JTextArea();
                        jScrollPane2.setViewportView(jTxtDesciption);
                        jTxtDesciption.setBackground(new java.awt.Color(255,
                                255, 240));
                        jTxtDesciption.setForeground(new java.awt.Color(0, 0,
                                255));
                        jTxtDesciption.setPreferredSize(new java.awt.Dimension(
                                288, 27));
                    }
                }
                {
                    jLabel4 = new JLabel();
                    getContentPane().add(jLabel4);
                    jLabel4.setText("Parametre zobrazenia");
                    jLabel4.setBounds(311, 353, 222, 14);
                    jLabel4.setForeground(new java.awt.Color(100, 0, 0));
                }
                {
                    jTxtSettings = new JTextField();
                    getContentPane().add(jTxtSettings);
                    jTxtSettings.setBounds(311, 373, 293, 21);
                    jTxtSettings
                            .setBackground(new java.awt.Color(255, 255, 240));
                    jTxtSettings.setForeground(new java.awt.Color(0, 0, 255));
                }
                {
                    jLabel5 = new JLabel();
                    getContentPane().add(jLabel5);
                    jLabel5.setText("MIME typ");
                    jLabel5.setBounds(311, 406, 107, 14);
                    jLabel5.setForeground(new java.awt.Color(100, 0, 0));
                }
                {
                    jTxtMIME = new JTextField();
                    getContentPane().add(jTxtMIME);
                    jTxtMIME.setBounds(430, 403, 174, 21);
                    jTxtMIME.setBackground(new java.awt.Color(255, 255, 240));
                    jTxtMIME.setForeground(new java.awt.Color(0, 0, 255));
                    jTxtMIME.setEditable(false);
                }
            }
            this.setSize(628, 508);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Picture[] showDialog() {
        setModalityType(ModalityType.DOCUMENT_MODAL);
        setVisible(true);
        return ret;
    }

    private void jBtnCancelActionPerformed(ActionEvent evt) {
        jLstPicturesValueChanged(null);
        ret = null;
        setVisible(false);
    }

    private void jBtnOKActionPerformed(ActionEvent evt) {
        jLstPicturesValueChanged(null);
        int[] indices = jLstPictures.getSelectedIndices();
        ret = new Picture[indices.length];
        for (int i = 0; i < ret.length; i++)
            ret[i] = (Picture) pictures.get(indices[i]);

        setVisible(false);
    }

    private void jChbResizeStateChanged(ChangeEvent evt) {
        jPreview.setScaled(jChbResize.isSelected());
        jScrPreview.setViewportView(jPreview);
    }

    private void jBtnAddPictureActionPerformed(ActionEvent evt) {
        JFileChooser jfc = new JFileChooser(".");
        jfc.setFileFilter(new FileNameExtensionFilter("Podporované formáty",
                "jpg", "jpeg", "bmp", "gif", "png"));
        int state = jfc.showOpenDialog(this);
        if (state == JFileChooser.CANCEL_OPTION)
            return;

        File f = jfc.getSelectedFile();
        if (f == null)
            return;

        byte[] data = null;
        try {
            data = read(f.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        String name = f.getName();
        StringBuilder newName = new StringBuilder();

        for (int i = 0; i < name.lastIndexOf("."); i++) {

            if (((97 <= name.charAt(i)) && (name.charAt(i) <= 122))
                    || ((65 <= name.charAt(i)) && (name.charAt(i) <= 90))
                    || Character.isDigit(name.charAt(i)))
                newName.append(name.charAt(i));
            else
                newName.append("-");

        }
        for (int i = name.lastIndexOf("."); i < name.length(); i++)
            newName.append(name.charAt(i));
        String nazov = newName.toString();

        int i = 1;
        StringBuilder name2 = new StringBuilder();
        name2.append(nazov);
        try {
            while (pDao.existsPictureByName(name2.toString())) {
                System.out.println("som tu");
                name2 = new StringBuilder();
                name2.append(nazov);
                name2.insert(name2.lastIndexOf("."), i);

                i++;
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        Picture p = new Picture(name2.toString(), "", "",
                new MimetypesFileTypeMap(getClass().getResourceAsStream(
                        "/mime.types")).getContentType(f.getAbsolutePath()),
                data, null);
        pictures.addElement(p);
        // HOTFIX: stale sa zaktivni posledny pridany obrazok a hned sa prida po kliknuti na OK k otazke, cize staci + a OK a obrazok je v otazke, co je presne to, co nasa vlada (VV) chcela ;-)
        jLstPictures.setSelectedValue(p, true);
        //TODO
        try {
            pDao.addPicture(p);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void jLstPicturesValueChanged(ListSelectionEvent evt) {
        if (lastSel != null) {
            lastSel.setDescription(jTxtDesciption.getText());
            lastSel.setSettings(jTxtSettings.getText());
            try {
                pDao.updatePicture(lastSel);
            } catch (SQLException e) {
                hint("Error: " + e.getMessage());
            }
        }
        Picture sel = (Picture) jLstPictures.getSelectedValue();
        if (sel == null)
            return;
        lastSel = sel;
        jPreview.setImage(sel.getContent());
        jScrPreview.setViewportView(jPreview);
        jTxtDesciption.setText(sel.getDescription());
        jTxtSettings.setText(sel.getSettings());
        jTxtMIME.setText(sel.getMimeType());
    }

    private void hint(String text) {
        if (jTxtHint.getBackground() == GenexGUI.COMB1_BACKGROUND_COLOR) {
            jTxtHint.setBackground(GenexGUI.COMB2_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB2_FOREGROUND_COLOR);
        } else {
            jTxtHint.setBackground(GenexGUI.COMB1_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB1_FOREGROUND_COLOR);
        }
        if (text.startsWith("Error:")) {
            jTxtHint.setText(text.substring(6));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/error.png")));
        } else if (text.startsWith("Warning:")) {
            jTxtHint.setText(text.substring(8));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/warning.png")));
        } else if (text.startsWith("Info:")) {
            jTxtHint.setText(text.substring(5));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/info.png")));
        } else {
            jTxtHint.setText(text);
        }
    }

    public byte[] read(String file) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        byte[] data = new byte[(int) fc.size()];
        ByteBuffer bb = ByteBuffer.wrap(data);
        fc.read(bb);
        return data;
    }

}
